﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Data.Common;
using System.Data.Entity;
using View;
using Model;
using System.Xml.Serialization;
using System.IO;

namespace BLL
{
    public class DataContext
    {
        DataStorage database = null;

        public DataContext()
        {
            DbProviderFactory fact = DbProviderFactories.GetFactory("System.Data.SQLite.EF6");
            DbConnection connection = fact.CreateConnection();
            connection.ConnectionString = "Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "database\\ServiceCenter.db";
            connection.Open();
            database = new DataStorage(connection);
        }

        public static void Initialize()
        {
            //预先加载数据库文件，提升窗口打开速度
            DataContext context = new DataContext();
            context.DataRepertory.Nations.Load();
            //database.Nations.Load();
            //database.Professions.Load();
            //database.PoliticalStatuses.Load();
            //database.Relations.Load();
            //database.Areas.Load();
            //Console.WriteLine("Database Initialize completed.");


        }

        public DataStorage DataRepertory
        {
            get { return database; }
        }

        public void SaveChanges()
        {
            database.SaveChanges();
        }

        public void Update<T>(List<T> updateList)
        {
            var set = database.Set(typeof(T));
            updateList.ForEach(x =>
            {
                set.Attach(x);
                var entry = database.Entry((object)x);
                entry.State = EntityState.Modified;
            });
        }

        public void Insert<T>(List<T> addList)
        {
            var set = database.Set(typeof(T));
            addList.ForEach(x =>
            {
                set.Add(x);
            });
        }

        public void Delete<T>(List<T> deleteList)
        {
            var set = database.Set(typeof(T));
            deleteList.ForEach(x =>
            {
                set.Remove(x);
            });
        }

        public OperationResult DeleteProfessions(List<Profession> deleteList)
        {
            OperationResult result = new OperationResult();
            try
            {
                deleteList.ForEach(x =>
                {
                    if (database.Persons.Count(w => w.ProfessionID == x.ID) > 0)
                    {
                        result.Message.Add(x.Name + "已经被使用，无法删除！");
                    }
                    else
                    {
                        database.Professions.Remove(x);
                    }
                });
                SaveChanges();
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message.Add(ex.Message);
            }
            return result;
        }

        public OperationResult DeleteNations(List<Nation> deleteList)
        {
            OperationResult result = new OperationResult();
            try
            {
                deleteList.ForEach(x =>
                {
                    if (database.Persons.Count(w => w.NationID == x.ID) > 0)
                    {
                        result.Message.Add(x.Name + "已经被使用，无法删除！");
                    }
                    else
                    {
                        database.Nations.Remove(x);
                    }
                });
                SaveChanges();
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message.Add(ex.Message);
            }
            return result;
        }

        public OperationResult DeletePoliticalStatus(List<PoliticalStatus> deleteList)
        {
            OperationResult result = new OperationResult();
            try
            {
                deleteList.ForEach(x =>
                {
                    if (database.Persons.Count(w => w.PoliticalStatusID == x.ID) > 0)
                    {
                        result.Message.Add(x.Name + "已经被使用，无法删除！");
                    }
                    else
                    {
                        database.PoliticalStatuses.Remove(x);
                    }
                });
                SaveChanges();
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message.Add(ex.Message);
            }
            return result;
        }

        public OperationResult DeleteRelations(List<Relation> deleteList)
        {
            OperationResult result = new OperationResult();
            try
            {
                deleteList.ForEach(x =>
                {
                    if (database.Persons.Count(w => w.RelationID == x.ID) > 0)
                    {
                        result.Message.Add(x.Name + "已经被使用，无法删除！");
                    }
                    else
                    {
                        database.Relations.Remove(x);
                    }
                });
                SaveChanges();
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message.Add(ex.Message);
            }
            return result;
        }

        public OperationResult DeleteAreas(List<Area> deleteList)
        {
            OperationResult result = new OperationResult();
            try
            {
                deleteList.ForEach(x =>
                {
                    if (database.Persons.Count(w => w.AreaID == x.ID) > 0)
                    {
                        result.Message.Add(x.Name + "已经被使用，无法删除！");
                    }
                    else
                    {
                        database.Areas.Remove(x);
                    }
                });
                SaveChanges();
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message.Add(ex.Message);
            }
            return result;
        }

        public void InsertOrUpdate<T>(List<T> list)
        {
            var set = database.Set(typeof(T));
            list.ForEach(x =>
            {
                var state = database.Entry((object)x).State;
                switch (state)
                {
                    case EntityState.Modified:
                    case EntityState.Unchanged:
                    case EntityState.Deleted:
                        break;
                    default:
                        set.Add(x);
                        break;
                }
            });
            database.SaveChanges();
        }
    }
}
